package com.shop.cloud.common.security.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.shop.cloud.common.core.constant.CacheConstants;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.core.constant.SecurityConstants;
import com.shop.cloud.common.core.constant.enums.LoginTypeEnum;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.security.entity.BaseUser;
import com.shop.cloud.common.security.service.BaseUserDetailsService;
import com.shop.cloud.upms.common.dto.UserInfo;
import com.shop.cloud.upms.common.entity.SysUser;
import com.shop.cloud.upms.common.feign.FeignUserService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户详细信息
 *
 * @author 辰
 * @date 2023年10月26日17:35:32
 */
@Slf4j
@Primary
@Service
@AllArgsConstructor
public class BaseUserDetailsServiceImpl implements BaseUserDetailsService {
	private final FeignUserService feignUserService;
	@Autowired
	private  CacheManager cacheManager;

	/**
	 * 用户密码登录
	 *
	 * @param username 用户名
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {
		//查询缓存中是否有此用户信息，有则直接返回
		Cache cache = cacheManager.getCache(CacheConstants.USER_CACHE);
		if (cache != null && cache.get(username) != null) {
			return (BaseUser) cache.get(username).get();
		}
		//缓存中无此用户信息，feign查询
		R<UserInfo> result = feignUserService.info(username, SecurityConstants.FROM_IN);
		if(!result.isOk()){
			throw new RuntimeException(result.getMsg());
		}
		UserInfo info = result.getData();
		if(info == null){
			throw new RuntimeException("账号或密码错误");
		}
		UserDetails userDetails = getUserDetails(info);
		if(userDetails.isAccountNonLocked()){
			//合法用户，放入缓存
			cache.put(username, userDetails);
		}
		return userDetails;
	}

	/**
	 * 手机验证码登录
	 *
	 * @param phone
	 * @return UserDetails
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByPhone(String phone) {
		//查询缓存中是否有此用户信息，有则直接返回
		Cache cache = cacheManager.getCache(CacheConstants.USER_CACHE);
		if (cache != null && cache.get(phone) != null) {
			return (BaseUser) cache.get(phone).get();
		}
		R<UserInfo> result = feignUserService.infoByPhone(phone, SecurityConstants.FROM_IN);
		if(!result.isOk()){
			throw new RuntimeException(result.getMsg());
		}
		UserInfo info = result.getData();
		if(info == null){
			throw new RuntimeException("该手机号未绑定账号");
		}
		UserDetails userDetails = getUserDetails(info);
		if(userDetails.isAccountNonLocked()){
			//合法用户，放入缓存
			cache.put(phone, userDetails);
		}
		return userDetails;
	}

	/**
	 * 第三方登录,openId登录
	 *
	 * @param openId
	 * @return UserDetails
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByThirdParty(String type, String openId) {
		R<UserInfo> result = feignUserService.infoByThirdParty(type, openId, SecurityConstants.FROM_IN);
		if(!result.isOk()){
			throw new RuntimeException(result.getMsg());
		}
		UserInfo info = result.getData();
		if(info == null){
			throw new RuntimeException("该"+ LoginTypeEnum.valueOf(type).getDescription() + "未绑定账号");
		}
		return getUserDetails(info);
	}

	/**
	 * 构建userdetails
	 *
	 * @param info 用户信息
	 * @return
	 */
	public UserDetails getUserDetails(UserInfo info) {


		Set<String> dbAuthsSet = new HashSet<>();

		if (ArrayUtil.isNotEmpty(info.getRoles())) {
			// 获取角色
			Arrays.stream(info.getRoles()).forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role));
			// 获取资源
			dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

		}

		Collection<GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		SysUser user = info.getSysUser();
		boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL);
		// 构造security用户
		return new BaseUser(user.getId(), user.getOrganId(),user.getType(), user.getTenantId(), user.getShopId(), user.getSupplierId(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(),user.getTenantIds(), enabled,
				true, true, enabled, authorities);
	}

	@Override
	public int getOrder() {
		return Integer.MIN_VALUE;
	}
}
